# -*- coding: utf-8 -*-
# frontend/pages/01_📊_性能监控.py
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import time
from datetime import datetime, timedelta
import random

st.set_page_config(
    page_title="📊 性能监控",
    page_icon="📊",
    layout="wide"
)

def generate_mock_data():
    """生成模拟监控数据"""
    now = datetime.now()
    times = [now - timedelta(minutes=i) for i in range(60, 0, -1)]
    
    return {
        'timestamps': times,
        'cpu_usage': [random.uniform(20, 80) for _ in times],
        'memory_usage': [random.uniform(30, 70) for _ in times],
        'response_time': [random.uniform(0.5, 3.0) for _ in times],
        'request_count': [random.randint(10, 100) for _ in times]
    }

def main():
    st.title("📊 系统性能监控")
    st.markdown("---")
    
    # 实时指标卡片
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric(
            label="🔥 CPU使用率",
            value="45.2%",
            delta="2.1%",
            delta_color="inverse"
        )
    
    with col2:
        st.metric(
            label="💾 内存使用率",
            value="62.8%",
            delta="-1.5%",
            delta_color="normal"
        )
    
    with col3:
        st.metric(
            label="⚡ 平均响应时间",
            value="1.24s",
            delta="0.15s",
            delta_color="inverse"
        )
    
    with col4:
        st.metric(
            label="📈 请求总数",
            value="2,847",
            delta="156",
            delta_color="normal"
        )
    
    st.markdown("---")
    
    # 图表区域
    chart_col1, chart_col2 = st.columns(2)
    
    # 生成模拟数据
    data = generate_mock_data()
    df = pd.DataFrame(data)
    
    with chart_col1:
        st.subheader("🖥️ 系统资源使用情况")
        
        fig_resources = go.Figure()
        fig_resources.add_trace(go.Scatter(
            x=df['timestamps'],
            y=df['cpu_usage'],
            mode='lines+markers',
            name='CPU使用率',
            line=dict(color='#FF6B6B', width=3)
        ))
        fig_resources.add_trace(go.Scatter(
            x=df['timestamps'],
            y=df['memory_usage'],
            mode='lines+markers',
            name='内存使用率',
            line=dict(color='#4ECDC4', width=3)
        ))
        
        fig_resources.update_layout(
            xaxis_title="时间",
            yaxis_title="使用率 (%)",
            hovermode='x unified',
            showlegend=True,
            height=400
        )
        
        st.plotly_chart(fig_resources, use_container_width=True)
    
    with chart_col2:
        st.subheader("📊 响应性能分析")
        
        fig_performance = go.Figure()
        fig_performance.add_trace(go.Scatter(
            x=df['timestamps'],
            y=df['response_time'],
            mode='lines+markers',
            name='响应时间',
            line=dict(color='#45B7D1', width=3),
            yaxis='y'
        ))
        fig_performance.add_trace(go.Scatter(
            x=df['timestamps'],
            y=df['request_count'],
            mode='lines+markers',
            name='请求数量',
            line=dict(color='#96CEB4', width=3),
            yaxis='y2'
        ))
        
        fig_performance.update_layout(
            xaxis_title="时间",
            yaxis=dict(title="响应时间 (s)", side="left"),
            yaxis2=dict(title="请求数量", side="right", overlaying="y"),
            hovermode='x unified',
            showlegend=True,
            height=400
        )
        
        st.plotly_chart(fig_performance, use_container_width=True)
    
    # 模型性能表格
    st.subheader("🤖 模型性能统计")
    
    model_data = {
        '模型名称': ['GPT-4', '文心一言', '通义千问', 'Claude'],
        '平均响应时间': ['2.3s', '1.8s', '2.1s', '2.5s'],
        '成功率': ['99.2%', '98.7%', '99.1%', '98.9%'],
        '今日请求数': ['1,234', '987', '1,456', '876'],
        '错误数': ['10', '13', '12', '9'],
        '状态': ['🟢 正常', '🟢 正常', '🟢 正常', '🟢 正常']
    }
    
    model_df = pd.DataFrame(model_data)
    st.dataframe(model_df, use_container_width=True)
    
    # 自动刷新
    if st.button("🔄 刷新数据", use_container_width=True):
        st.rerun()
    
    # 自动刷新选项
    auto_refresh = st.checkbox("🔄 自动刷新 (30秒)")
    if auto_refresh:
        time.sleep(30)
        st.rerun()

if __name__ == "__main__":
    main()
